//
//  ReplayViewController.swift
//  SSCommentUI
//
//  Created by 松松 on 2019/5/27.
//

import UIKit
import SSComment
import SSBaseTool
import MJRefresh
import SSIconFont

class ReplayViewController: UIViewController {

    private var tableView : BaseTableView!
    private var tableData = [CommentListModel]()//可修改为需要的数据类型
    private var heightData = [HeightModel]()
    private let VM = SSCommentViewModel()

    var colorModel = SSCommentColorModel()
    var commentModel : CommentListModel!

    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        getData()
        setEvent()

        tableView.estimatedRowHeight = 44

    }


    //MARK:设置UI
    func setUI(){

        view.backgroundColor = UIColor(hexString: colorModel.bgColor)
        tableView = BaseTableView(frame: CGRect.zero, style: .plain)
        tableView.frame = CGRect(x: 0, y: STATUES_HEIGHT+44, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - 44 - STATUES_HEIGHT - BOTTOM_SAFE_HEIGHT)
        tableView.backgroundColor = UIColor(hexString: colorModel.bgColor)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.baseTableViewDelegate = self
        tableView.separatorStyle = .none
        self.view.addSubview(tableView)
        tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: 0.01))
        tableView.tableFooterView = UIView()

        tableView.register(UINib(nibName: "SSCommentsTableViewCell", bundle: Bundle.getCurrentFramwork()), forCellReuseIdentifier: "SSCommentsTableViewCell")//Bundle.getPodChildBundle(name: "SSCommentUI")

        (tableView.mj_header as! MJRefreshNormalHeader).stateLabel?.textColor = UIColor(hexString: colorModel.refreshTextColor)
        (tableView.mj_header as! MJRefreshNormalHeader).lastUpdatedTimeLabel?.textColor = UIColor(hexString: colorModel.refreshTextColor)
        automaticallyAdjustsScrollViewInsets = false
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {

        }
    }

    //MARK:获取数据
    func getData(){
        tableView.mj_header?.beginRefreshing()
    }

    //MARK:设置事件
    func setEvent(){

    }

    //MARK:点赞某条评论
    @objc
    private func likeComment(_ sender: UIButton){
        if userModel.fromUserId == nil{
            unowned let weakSelf = self
            commentLoginBlock?(weakSelf)
            return
        }
        var model : CommentListModel
        model = tableData[sender.ss_indexPath.row]

        if sender.isSelected{//已经点赞过的取消点赞
            VM.cancelLike(appCode: APP_CODE, toItemCode: model.id!, mainTypeCode: "1", formUserId: userModel.fromUserId!, success: { (modelData) in
                model.isLike = false
                let likeNum = model.likeNum ?? 0
                model.likeNum = likeNum
                model.likeNum! -= 1
                self.tableView.reloadRows(at: [sender.ss_indexPath], with: .none)
            }) { (err) in
                ssPrint(err)
            }
        }else{//点赞
            VM.like(appCode: APP_CODE, fromUserName: userModel.fromUserName ?? "", fromUserHead: userModel.fromUserHead ?? "", toItemCode: model.id!, goodType: 1, mainTypeCode: "1", formUserId: userModel.fromUserId!, success: { (modelData) in
                model.isLike = true
                let likeNum = model.likeNum ?? 0
                model.likeNum = likeNum
                model.likeNum! += 1
                self.tableView.reloadRows(at: [sender.ss_indexPath], with: .none)
            }) { (err) in
                ssPrint(err)
            }
        }
    }

    //MARK:点击回复按钮
    @objc
    private func replayComment(_ sender: UIButton){
        replay(sender.ss_indexPath)
    }

    //MARK:回复某条评论
    private func replay(_ indexPath: IndexPath){
        if userModel.fromUserId == nil{
            unowned let weakSelf = self
            commentLoginBlock?(weakSelf)
            return
        }
        var model : CommentListModel
        model = tableData[indexPath.row]
        let vc = CommentTextFieldViewController(placeholder: "回复\(model.fromUserName ?? "")...", placeholderColor: UIColor.lightGray, maxLength: COMMENT_MAX_CONTENT) { (text) in
            self.VM.addComment(appCode: APP_CODE, fromUserName: userModel.fromUserName!, fromUserHead: userModel.fromUserHead!, formUserId: userModel.fromUserId!, commentImages: nil, replyCommentId: model.id!, commentId: model.id!, mainTypeCode: userModel.mainTypeCode!, toItemCode: model.toItemCode!, commentContent: text, success: { (modelData) in

                var num = model.commentReplyNum ?? 0
                num += 1
                model.commentReplyNum = num
                model.cmComment = modelData
                self.heightData.removeAll()
                self.tableView.reloadData()

            }, error: { (err) in

            })
        }
        self.present(vc, animated: true, completion: nil)
    }

}

extension ReplayViewController : BaseTableViewDelegate{
    func getDate(tableView: BaseTableView, pageNum: Int, pageSize: Int) {
        VM.getCommentList(appCode: APP_CODE, replyCommentId: commentModel.id!, mainTypeCode: commentModel.mainTypeCode!, toItemCode: commentModel.toItemCode!, commentSate: 1, pageSize: pageSize, pageNumber: pageNum, success: { (modelData) in
            if pageNum == FIRST_PAGE_NUM{
                self.tableData = modelData
            }else{
                self.tableData.append(contentsOf: modelData)
            }
            tableView.pushSuccess(count: modelData.count)
        }) { (error) in
            ssPrint(error)
            if pageNum == FIRST_PAGE_NUM{
                tableView.pushSuccess(count: 0)
            }
        }
    }

}

extension ReplayViewController : UITableViewDelegate,UITableViewDataSource{

    //MARK:tableView代理&数据源
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {


        if heightData.count > indexPath.section
            && heightData[indexPath.section].heights.count > indexPath.row {
            return heightData[indexPath.section].heights[indexPath.row]
        }
        return UITableViewAutomaticDimension
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(SSCommentsTableViewCell.self)
        var model : CommentListModel
        model = tableData[indexPath.row]

        cell.contentView.backgroundColor = UIColor(hexString: colorModel.bgColor)
        cell.nameLabel.textColor = UIColor(hexString: colorModel.commentNameColor)
        cell.timeLabel.textColor = UIColor(hexString: colorModel.timeColor)
        cell.contentLabel.textColor = UIColor(hexString: colorModel.commentContentColor)
        cell.replayView.layer.backgroundColor = UIColor(hexString: colorModel.replayBGColor).cgColor
        cell.replayLabel.textColor = UIColor(hexString: colorModel.replayContentColor)
        cell.likeButton.setTitleColor(UIColor(hexString: colorModel.numNormalColor), for: .normal)
        cell.likeButton.setTitleColor(UIColor(hexString: colorModel.numSelectColor), for: .selected)
        cell.commentButton.setTitleColor(UIColor(hexString: colorModel.numNormalColor), for: .normal)

        cell.avtarImageView.loadUrl(url: model.fromUserHead)
        cell.nameLabel.text = model.fromUserName
        cell.timeLabel.text = model.getTime()
        cell.contentLabel.text = model.commentContent
        let likeNum = model.likeNum ?? 0
        var likeStr = ""
        if likeNum < 99{
            likeStr = "\(likeNum)"
        }else{
            likeStr = "99+"
        }
        let replayNum = model.commentReplyNum ?? 0
        var replayStr = ""
        if replayNum < 99{
            replayStr = "\(replayNum)"
        }else{
            replayStr = "99+"
        }
        cell.likeButton.setFontTitle(text: "\(SSIconText.ico_goode626.rawValue) \(likeStr)", size: 12, state: .normal)
        cell.likeButton.setFontTitle(text: "\(SSIconText.ico_good1e644.rawValue) \(likeStr)", size: 12, state: .selected)
        cell.commentButton.setFontTitle(text: "\(SSIconText.ico_commente625.rawValue) \(replayStr)", size: 12, state: .normal)
        cell.likeButton.isSelected = model.isLike ?? false

        if model.cmComment?.commentContent == nil{
            cell.replayView.isHidden = true
            //            cell.replayButton.hiddenUpDown()
            cell.replayLabel.text = ""
        }else{
            cell.replayView.isHidden = false

            let replay = "\(model.cmComment?.fromUserName ?? ""):\(model.cmComment?.commentContent ?? "")"
            cell.replayLabel.attributedText = replay.heightLight(changeColor: UIColor(hexString: colorModel.replayNameColor), if: "\(model.cmComment?.fromUserName ?? "")")
        }

        //优化性能 缓存高度
        func addHeightModel(){
            if heightData.count <= indexPath.section{
                let newHeight = HeightModel()
                newHeight.heights = []
                heightData.append(newHeight)
                addHeightModel()
            }else{
                return
            }
        }
        addHeightModel()
//        let heightModel = heightData[indexPath.section]
//        if heightModel.heights.count <= indexPath.row{
//            var height = cell.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
//            if model.cmComment?.commentContent == nil{
//                height -= 37
//            }
//            heightModel.heights.append(height)
//        }

        cell.likeButton.ss_indexPath = indexPath
        cell.likeButton.addTarget(self, action: #selector(likeComment(_:)), for: .touchUpInside)
        cell.commentButton.ss_indexPath = indexPath
        cell.commentButton.addTarget(self, action: #selector(replayComment(_:)), for: .touchUpInside)

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        replay(indexPath)
    }


}
